const path = require('path');
const Webpack = require('webpack');
const WEB_SITE = 'mobile';
const TYPE_ENV = process.env.TYPE_ENV
const prodFlag = TYPE_ENV === 'prod';

const config = {
  projectName: 'mini-program-taro',
  date: '2019-5-22',
  designWidth: 750,
  deviceRatio: {
    '640': 2.34 / 2,
    '750': 1,
    '828': 1.81 / 2,
  },
  sourceRoot: 'src',
  //多端打包不同的dist
  outputRoot: `dist/${process.env.TARO_ENV}`,
  alias: {
    '@/assets': path.resolve(__dirname, '..', 'src/assets'),
    '@/tpl-assets': path.resolve(__dirname, '..', 'node_modules/@wanmi/ui-taro/lib/assets/templates'),
    '@/common': path.resolve(__dirname, '..', 'src/common'),
    '@/pages': path.resolve(__dirname, '..', 'src/pages'),
    '@/service': path.resolve(__dirname, '..', 'src/service'),
    '@/redux': path.resolve(__dirname, '..', 'src/redux'),
    '@/utils': path.resolve(__dirname, '..', 'src/utils'),
    '@/libs': path.resolve(__dirname, '..', 'src/libs'),
    api: path.resolve(__dirname, '..', 'src/webapi'),
    wmkit: path.resolve(__dirname, '..', 'src/wmkit/common'),
    '@/wmkit': path.resolve(__dirname, '..', 'src/wmkit'),
    config: path.resolve(__dirname, '..', 'src/wmkit/config'),
    '@/plugin': path.resolve(__dirname, '..', 'src/biz-plugins'),
    immutable: path.resolve(__dirname, '..', 'src/wmkit/common/immutable.min.js'),
    '@/*': path.resolve(__dirname, '..', 'src/*'),
  },
  terser: {
    enable: true,
    config: {
      warnings: false,
      compress: {
        drop_debugger: true,
        drop_console: true,
        pure_funcs: ['console.log'],
      },
    },
  },
  csso: {
    enable: true,
    config: {
      restructure: false,
    },
  },
  sass: {
    // OR
    resource: [
      path.resolve(__dirname, '..', 'src/pages/common/style/swipe.scss'),
      path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/modal.scss'),
      path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/switch.scss'),
      path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/tab-bar.scss'),
      path.resolve(__dirname, '..', 'node_modules/taro-ui/dist/style/components/badge.scss'),
    ],
    projectDirectory: path.resolve(__dirname, '..'),
    data: '$nav-height: 48px;',
  },
  defineConstants: {},
  copy: {
    patterns: [],
    options: {},
  },
  // 框架，react，nerv，vue, vue3 等
  framework: 'react',
  mini: {
    enableSourceMap: false,
    // sourceMapType: 'source-map',
    postcss: {
      pxtransform: {
        enable: true,
        config: {
          remove: false,
        }
      },
      url: {
        enable: true,
        config: {
          limit: 1024 // 设定转换尺寸上限
        }
      },
      cssModules: {
        enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
        config: {
          namingPattern: 'module', // 转换模式，取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    },
    webpackChain(chain, webpack) {
      // 将 lodash 单独拆分出来 (防止vendors.js过大)
      chain.plugin('ignore').use(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/));
      chain.merge({
        optimization: {
          splitChunks: {
            cacheGroups: {
              lodash: {
                name: 'lodash',
                priority: 1000,
                test(module) {
                  return /node_modules[\\/]lodash/.test(module.context);
                },
              },
            },
          },
        },
        resolve: {
          alias: {
            // react: 'nervjs',
            // 'react-dom': 'nervjs',
          },
        },
      });
      chain.merge({
        plugin: {
          install: {
            plugin: require('terser-webpack-plugin'),
            args: [{
              parallel: true,
              extractComments: true,
              terserOptions: {
                compress: true, // 默认使用terser压缩
                // mangle: false,
                keep_classnames: true, // 不改变class名称
                keep_fnames: true // 不改变函数名称
              }
            }]
          }
        }
      })
    },
    commonChunks(commonChunks) {
      // 添加 lodash 公共文件
      commonChunks.push('lodash');
      return commonChunks;
    },
    lessLoaderOption: {
      lessOptions: {
        paths: [path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, '..', 'src')],
      }
    },
    imageUrlLoaderOption: {
      esModule: false,
    },
    optimizeMainPackage: {
      enable: true
    },
    miniCssExtractPluginOption: {
      ignoreOrder: true,
    }
  },
  h5: {
    publicPath: `/${WEB_SITE}/`,
    staticDirectory: 'static',
    esnextModules: ['taro-ui', '@wanmi/ui-taro', '@wanmi'],
    output: {
      filename: 'js/[name].[hash].js',
      chunkFilename: 'js/[name].[chunkhash].js',
      // sourceMapFilename: "js/[name].js.map",
    },
    framework: 'react',
    miniCssExtractPluginOption: {
      filename: 'css/[name].[hash].css',
      chunkFilename: 'css/[name].[chunkhash].css',
    },
    router: {
      mode: 'browser',
      basename: `/${WEB_SITE}`,
    },
    enableSourceMap: !prodFlag,
    sourceMapType: 'cheap-module-source-map',
    postcss: {
      autoprefixer: {
        enable: true,
        config: {},
      },
      cssModules: {
        enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
        config: {
          namingPattern: 'module', // 转换模式，取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]',
        },
      },
    },
    webpackChain(chain) {
      // 将 lodash 单独拆分出来 (防止vendors.js过大)
      // chain.plugin('analyzer')
      //   .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
      // chain
      // .plugin("sentry")
      //   .use(
      //     new SentryWebpackPlugin({
      //       configFile: '.sentryclirc',
      //       include: "./dist/h5/js",
      //       ignore: ["node_modules", "webpack.config.js"],
      //       release: 'mobile-project@' + Release,
      //     }),)
      chain.plugin('htmlWebpackPlugin').tap(args => {
        args[0].publicPath = `/${WEB_SITE}/`;
        args[0].TYPE_ENV = `${TYPE_ENV}`;
        return args;
      })
      chain.merge({
        optimization: {
          splitChunks: {
            cacheGroups: {
              lodash: {
                name: 'lodash',
                priority: 1000,
                test(module) {
                  return /node_modules[\\/]lodash/.test(module.context);
                },
              },
            },
          },
        },
        resolve: {
          // alias: {
          //   react: 'nervjs',
          //   'react-dom': 'nervjs',
          // },
        },
      });
      // 增加 - 编辑进度提示
      chain.merge({
        plugin: {
          install: {
            plugin: new Webpack.ProgressPlugin(),
          }
        }
      });
    },
    commonChunks(commonChunks) {
      // 添加 lodash 公共文件
      commonChunks.push('lodash');
      return commonChunks;
    },
    lessLoaderOption: { lessOptions: { paths: [path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, '..', 'src')] } },
    imageUrlLoaderOption: {
      esModule: false,
    },
    devServer: {
      host: '0.0.0.0',
      hot: false,
      openPage: `${WEB_SITE}/`,
    },
    // webpackChain(chain) {
    //   chain.merge({
    //     optimization: {
    //       usedExports: true,
    //     },
    //   });
    // },
  },
};

module.exports = function (merge) {
  return merge({}, config, require('./build'));
};
